<template>
  <el-dialog
    title="添加游玩点"
    :visible.sync="pushPointState"
    :close-on-click-modal="false"
    @close="TICancel"
  >
    <div class="img-text">
      <el-form
        label-position="top"
        :model="Form"
        ref="dialogPointForm"
        label-width="150px"
        class="demo-dynamic"
      >
        <el-form-item
          :rules="rules.title"
          prop="title"
          label="游玩标题"
          v-if="Form.title===''||Form.title?true:false"
        >
          <el-input size="mini" v-model="Form.title" :maxlength="Form.titleMax" show-word-limit></el-input>
        </el-form-item>
        <el-form-item
          :rules="rules.playTime"
          prop="play_time"
          label="游玩时长(小时单位)"
          v-if="mainOption.name==='strategy'?false:true"
        >
          <el-input-number
            v-if="mainOption.name==='strategy'?false:true"
            size="mini"
            v-model="Form.play_time"
            :precision="1"
            :step="0.1"
            :min="1"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div class="content">
        <draggable v-model="dataContent" :options="{group:'people'}">
          <div
            v-for="(stepCon, stepConIndex) in dataContent"
            :key="stepConIndex"
            style="margin: 20px 0;"
          >
            <div
              v-if="stepCon.type == 'text'"
              style="border:1px dotted #cccccc;border-radius: 4px;margin: 5px;position: relative;"
            >
              <div
                style="line-height: 2;padding-left: 5px"
                @click="pointTextClick(stepCon.val, stepConIndex)"
                v-html="replaceN(stepCon.val)"
              >
                <!-- {{}} -->
              </div>
              <el-popover trigger="click" placement="top" width="160" v-model="stepCon.IsDel">
                <p>确定删除内容吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="stepConCancel(stepConIndex)">取消</el-button>
                  <el-button type="primary" size="mini" @click="stepConDel(stepConIndex)">确定</el-button>
                </div>
                <span
                  class="el-icon-error"
                  slot="reference"
                  style="position: absolute;top:0;right:0;color: salmon;font-size: 20px;transform: translateX(40%) translateY(-40%)"
                ></span>
              </el-popover>
            </div>
            <div v-else style="position: relative">
              <!-- <el-image :src="'http://'+stepCon.imgList.url"></el-image> -->
              <el-image :src="stepCon.imgList.url" @click="pointIMgClick(stepCon.imgList.url, stepConIndex)" lazy></el-image>
              <el-popover placement="top" width="160" v-model="stepCon.IsDel">
                <p>确定删除内容吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="stepCon.IsDel = false">取消</el-button>
                  <el-button type="primary" size="mini" @click="stepConDel(stepConIndex)">确定</el-button>
                </div>
                <span
                  class="el-icon-error"
                  slot="reference"
                  style="position: absolute;top:0;right:0;color: salmon;font-size: 20px"
                ></span>
              </el-popover>
            </div>
          </div>
        </draggable>
      </div>
      <div class="btnGroup" style="display: flex;justify-content: flex-end;">
        <el-button size="mini" type="primary" @click="stepAddText">添加文本</el-button>
        <el-button size="mini" type="primary" @click="stepAddImg">添加图片</el-button>
      </div>
      <!-- 资源选择 :option-state="optionState" :resource-comp-form="Form"  :server-data="pointInResourceData"-->
      <div v-if="Form.resources?true:false">
        <resource-comp
          :append-to-body="appendToBody"
          :point-resource-option="pointResourceOption"
          :resource-comp-form="Form"
          :rules-resource="rulesResource"
          ref="resourceComp"
          @transmit-change-arr="transmitChangeArr"
          @scroll-more="scrollMore"
          transmit-name="imgText"
        ></resource-comp>
      </div>
      <!-- 图片上传加载中 -->
      <!-- 全局text编辑 :transmit-val="transmitVal" :option-text="optionText" -->
      <dialog-text-edit
        :add-text-state-num="addTextStateNum"
        :append-to-body="appendToBody"
        @text-edit-transmit="textEditTransmit"
        @text-edit-updata-transmit="textEditUpdataTransmit"
        :transmit-val="nowObj"
        :step-index="stepIndex"
        :is-updata="isUpdata"
        @text-edit-cancel-transmit="textEditCancelTransmit"
        ref="imgTextDialogText"
        :main-option="mainOption"
      ></dialog-text-edit>
      <!-- 全局裁剪 -->
      <dialog-img-edit
        :is-img-updata="isImgUpdata"
        :append-to-body="appendToBody"
        :dialog-img-add-num="dialogImgAddNum"
        :Img-utils-title="ImgUtilsTitle"
        @img-url-transmit="imgUrlTransmit"
        :cropper-option-data="cropperOptionData"
        ref="imgTextDialogImg"
      ></dialog-img-edit>
    </div>
    <div class="btn-group">
      <el-button type="primary" size="small" @click="TICancel">取消</el-button>
      <el-button type="primary" size="small" @click="TIConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
// window.location.protocol+"//"+window.location.host
function http(url, method, data) {
  return new Promise((res, rej) => {
    axios({
      url,
      method,
      data
    })
      .then(pos => res(pos))
      .catch(err => rej(err));
  });
}
module.exports = {
  name: "imgText",
  data() {
    return {
      // 资源数据拉取
      // serverData: [],
      // 当前传递的数据
      nowObj: {
        val: ""
      },
      // 是否修改文本
      isUpdata: false,
      // 是否修改图片
      isImgUpdata: false,
      // 当前的content的index
      stepIndex: 0,
      // 点击文字修改所传的值
      transmitVal: "",
      progressShow: false,
      // 上传图片进度
      progress: 0,
      visible: false,
      dataContent: [],
      dialogImgAddNum: 0,
      // 点击添加文本一直加的数
      addTextStateNum: 0,
      // 是否打开内层dialog
      appendToBody: true,
      pushPointState: false,
      ImgUtilsTitle: "选择图片",
      // 全局裁剪显示状态
      addImg: false,
      Form: this.mainOption.tiOption,
      msg: "这是msg信息",
      clickMsg: "clickMsg",
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        playTime: [
          { required: true, message: "请输入游玩时长", trigger: "blur" }
        ]
      }
    };
  },
  components: {
    "dialog-text-edit": httpVueLoader("./dialogTextEdit.vue"),
    "dialog-img-edit": httpVueLoader("./dialogImgEdit.vue"),
    "resource-comp": httpVueLoader("./resourceComp.vue")
  },
  props: {
    pointResourceOption: {
      type: Object,
      default: () => {
        return {}
      }
    },
    mainOption: {
      type: Object,
      default: () => {
        return {};
      }
    },
    pointInResourceData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    rulesResource: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 全局输入框数字大小限制
    // optionText: {
    //   type: Object,
    //   default: () => {
    //     return {};
    //   }
    // },
    cropperOptionData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  methods: {
    scrollMore(name){
      this.$emit('scroll-more', name)
    },
    transmitChangeArr(arr) {
      // this.Form.optionState = arr;
      this.Form.resources = arr
    },
    // 图文混排数据提交
    TIConfirm() {
      const objdata = {
        title: "",
        play_time: null,
        content: [],
        resources: [],
        IsDel: false,
        pointTitleMax: this.Form.titleMax
      };
      objdata.title = this.Form.title;
      objdata.play_time = this.Form.play_time;
      objdata.content = this.dataContent;
      objdata.resources = this.Form.resources;
      console.log(objdata, this.Form.play_time, "objdataobjdata");
      this.formSubmit(objdata);
    },
    formSubmit(objdata) {
      let arr = [];
      let that = this;
      // 调用子组件的表单验证
      this.Form.resources ? arr.push(this.$refs.resourceComp.resourceCompSubmit()): null;
      arr.push(allCheckRules(that, "dialogPointForm"));

      Promise.all(arr)
        .then(() => {
          console.log(objdata, "objdataobjdata");
          this.$emit("transmit-imgtextdata", objdata);
          this.TICancel();
        })
        .catch(err => {
          this.$message({ message: "请填写完整信息", type: "warning" });
          console.log("err", arr);
        });
    },
    // 图文混排取消
    TICancel() {
      this.Form.title ? (this.Form.title = "") : null;
      this.content = [];
      this.Form.resources ? this.Form.resources = []: null;
      this.dataContent = [];
      this.Form.play_time?this.Form.play_time = 1:null;
      this.pushPointState = false;
      // 去掉resource的arr
      this.pointResourceOption.val = []
      // this.Form.title.val = "";
      // this.dataContent = [];
      // this.Form.optionState = [];
      // this.Form.playTime.val = 1;
      // this.pushPointState = false;
      // this.$set(this.Form, "optionState", []);
    },
    // 取消
    textEditCancelTransmit() {
      this.isUpdata = false;
    },
    // 修改后的值和事件传递
    textEditUpdataTransmit(str) {
      this.dataContent[this.stepIndex].val = str;
      this.isUpdata = false;
    },
    imgUrlTransmit(imgurl, isImgUpdata) {
      // const obj = { url: imgurl, type: "img", IsDel: false };
      const obj = { imgList: {url: imgurl}, type: "img", IsDel: false }
      const that = this;
      if (isImgUpdata) {
        // this.dataContent[this.stepIndex].url = imgurl;
        this.dataContent[this.stepIndex].imgList.url = imgurl;
      } else {
        this.dataContent.push(obj);
      }
    },
    replaceN(str) {
      if (str) {
        return str.replace(/\n/g, "<br>");
      }
    },
    // 添加text传来的
    textEditTransmit(str) {
      let obj = { val: "", type: "text", IsDel: false };
      obj.val = str;
      this.dataContent.push(obj);
      // console.log(this.dataContent)
    },
    stepAddImg() {
      console.log(this.$refs, "refs");
      this.isImgUpdata = false;
      this.$refs.imgTextDialogImg.$refs.myInput.value = "";
      this.$refs.imgTextDialogImg.$refs.myInput.click();
      this.ImgUtilsTitle = "添加图片";
      // this.addImg = true;
      // this.dialogImgAddNum++;
    },
    // 添加文本
    stepAddText() {
      this.$refs.imgTextDialogText.addText = true;
      // this.addTextStateNum++;
    },
    pointIMgClick(url, stepConIndex) {
      this.stepIndex = stepConIndex;
      this.isImgUpdata = true;
      this.$refs.imgTextDialogImg.cropperOptionData.img = url;
      this.ImgUtilsTitle = "裁剪图片";
      this.$refs.imgTextDialogImg.addImg = true;
    },
    // 确认删除
    stepConDel(stepConIndex) {
      this.dataContent.splice(stepConIndex, 1);
    },
    // 取消
    stepConCancel(stepConIndex) {
      this.dataContent[stepConIndex].IsDel = false;
    },
    // 修改文本
    pointTextClick(val, stepConIndex) {
      this.nowObj.val = val;
      // console.log(this.$children)
      this.isUpdata = true;
      // this.addTextStateNum++;
      this.$refs.imgTextDialogText.addText = true;
      this.transmitVal = val;
      this.stepIndex = stepConIndex;
    },
    handleDialogClose() {},
    divClick() {
      this.$emit("transmit-data", this.clickMsg);
    },
    uploadImgFn(imgUrl, Bucket, Region) {
      const that = this;
      return new Promise((res, rej) => {
        cos.sliceUploadFile(
          {
            Bucket,
            Region,
            Key: "images/" + new Date().getTime(),
            Body: imgUrl,
            onHashProgress: function(progressData) {
              console.log("校验中", JSON.stringify(progressData));
            },
            onProgress: function(progressData) {
              // , JSON.stringify(progressData)
              console.log("上传中", progressData.percent, progressData.speed);
              const progress =
                Math.round((progressData.loaded / progressData.total) * 10000) /
                100;
              that.progress = progress;
              var time;
              clearTimeout(time);
              time = setTimeout(() => {
                that.progressShow = false;
                that.progress = 0;
              }, 200);
              console.log(progress, "progress");
            }
          },
          (err, data) => {
            if (err) {
              rej(err);
            } else {
              res(data);
            }
          }
        );
      });
    }
  }
};
</script>
<style scoped>
.content {
  min-height: 400px;
}
.img-text {
  width: 100%;
  /* min-height: 300px; */
  border: 1px solid seagreen;
  padding: 10px;
  box-sizing: border-box;
}
.btn-group {
  margin-top: 30px;
}
</style>